import { Form, Input, Select, Space, Button, DatePicker, Avatar, Image, Modal, message } from "antd";
import { SearchOutlined, UserOutlined } from "@ant-design/icons";
import ThePagination from "@/components/ThePagination";
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import TheDialog from "@/components/TheDialog";
import TheImage from "@/components/TheImage";
import React, { useRef, useState } from "react";
import { ExclamationCircleFilled } from "@ant-design/icons";
import "./style/style.less";
import Banned from "./component/Banned";
import { apiGetUserList, apiPetArchivesPage, apiMemberInfoExport } from '@/request/users'
import { getDateTime3 } from '@/utils/getDate'
import store from "@/store/store"
import _ from 'lodash';
import HandleDialog from '@/views/riskControl/components/handleDialog'

import _connect from "../../_connect";
import moment from 'moment'
import QRCode from "qrcode.react";
import domtoimage from "dom-to-image"
import logoUrl from '@/assets/images/qrlogo.png'
import { exportSheetTable } from '@/utils/exportTable.js'
import {maskNumber} from '@/utils/tools'

const { RangePicker } = DatePicker;

const SearchHeader = ({ getSearchValue, resetValue, totalCount }) => {
  const formRef = useRef()
  const searchValue = store.getState().searchValue || {}
  const defaultmemberType = searchValue.memberType === "R" ? "注册会员" : searchValue.memberType === "P" ? "正式会员" : searchValue.memberType === "S" ? "商户会员" : "请选择用户身份"
  const defaultmemberStatus = searchValue.memberStatus === "Y" ? "正常" : searchValue.memberStatus === "N" ? "冻结" : "请选择用户状态"
  const formSubmit = value => {
    if (!_.isEmpty(value.time)) {
      value.memberCreatedTimeStart = getDateTime3(value.time[0])
      value.memberCreatedTimeEnd = getDateTime3(value.time[1])
    }
    delete (value.time)
    value = {
      ...value,
    }
    _.forIn(value, (v, k) => {
      if (!v) {
        delete (value[k])
      }
    })
    getSearchValue(value)
    return value
  }
  const reset = () => {
    formRef.current.setFieldsValue({
      memberId: '',
      wxNickName: '',
      memberMobile: '',
      memberType: null,
      memberStatus: null,
      parentMemberId: '',
      parentNickName: '',
      time: [],
    })
    getSearchValue({})
  };
  // 导出
  let exportLoading = false
  const exportList = () => {
    console.log(totalCount)
    exportLoading = true;
    //当查询数据超出设置阈值时进行拦截提示
    if (totalCount > 5000) {
      message.warning('当前导出数量过大,请进行数据筛选查询后尝试');
      return
    }
    apiMemberInfoExport({ ...searchValue }).then(res => {
      if (res.code === 0) {
        let tH_data = [
          { prop: "memberId", title: '用户ID' },
          { prop: "nickName", title: '昵称' },
          { prop: "memberMobile", title: '手机号' },
          { prop: "memberType", title: '身份' },
          { prop: "memberStatus", title: '状态' },
          { prop: "parentMemberId", title: '推荐人ID' },
          { prop: "parentNickName", title: '推荐人昵称' },
          { prop: "memberCreatedTime", title: '注册时间' }
        ],
          tB_data = res.data.map(item => {
            return {
              memberId: item.memberId,
              nickName: item.nickName,
              memberMobile: item.memberMobile,
              memberType: item.memberType === "R" ? "注册会员" : item.memberType === "P" ? "正式会员" : item.memberType === "S" ? "商户会员" : "/",
              memberStatus: item.memberStatus === "Y" ? "正常" : item.memberStatus === "N" ? "冻结" : "/",
              parentMemberId: item.parentMemberId,
              parentNickName: item.parentNickName,
              memberCreatedTime: item.memberCreatedTime,
            }
          })
        const option = { fileName: '用户列表', tH_data, tB_data, isSheet: true, merge: false }
        exportSheetTable(option)
      }
    })
  }
  return (
    <div className="p-search-box service-list-sarch">
      <Form ref={formRef} onFinish={formSubmit} layout="inline">
        <Form.Item name={"memberId"}>
          <Input
            style={{ width: 120 }}
            suffix={<SearchOutlined />}
            placeholder={"请输入ID"}
            defaultValue={searchValue.memberId}
          />
        </Form.Item>
        <Form.Item name={"wxNickName"}>
          <Input
            style={{ width: 120 }}
            suffix={<SearchOutlined />}
            placeholder={"请输入昵称"}
            defaultValue={searchValue.wxNickName}
          />
        </Form.Item>
        <Form.Item name={"memberMobile"}>
          <Input
            style={{ width: 140 }}
            suffix={<SearchOutlined />}
            placeholder={"请输入手机号"}
            defaultValue={searchValue.memberMobile}
          />
        </Form.Item>
        <Form.Item name={"parentMemberId"}>
          <Input
            style={{ width: 140 }}
            suffix={<SearchOutlined />}
            placeholder={"请输入推荐人Id"}
            defaultValue={searchValue.parentMemberId}
          />
        </Form.Item>
        <Form.Item name={"parentNickName"}>
          <Input
            style={{ width: 140 }}
            suffix={<SearchOutlined />}
            placeholder={"请输入推荐人昵称"}
            defaultValue={searchValue.parentNickName}
          />
        </Form.Item>
        <Form.Item name={"memberType"}>
          <Select
            style={{ width: 140 }}
            options={[{ value: 'R', label: "注册会员" }, { value: 'P', label: "正式会员" }, { value: 'S', label: "商户会员" }]}
            placeholder={defaultmemberType}
          />
        </Form.Item>
        <Form.Item name={"memberStatus"}>
          <Select
            style={{ width: 140 }}
            options={[{ value: 'Y', label: "正常" }, { value: 'N', label: '冻结' }]}
            placeholder={defaultmemberStatus}
          // defaultValue={defaultmemberStatus}
          />
        </Form.Item>
        <Form.Item name={"time"} label="注册时间">
          <RangePicker format={'YYYY/MM/DD'} defaultValue={searchValue.hasOwnProperty('memberCreatedTimeStart') ? [moment(searchValue.memberCreatedTimeStart, 'YYYY/MM/DD'), moment(searchValue.memberCreatedTimeEnd, 'YYYY/MM/DD')] : []} />
        </Form.Item>
        <Form.Item>
          <Space size="small" style={{ marginLeft: 10 }}>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button onClick={reset}>重置</Button>
            <TheButton size="middle" type="default" loading={exportLoading} haspermi={['user:exportList']} onClick={exportList}>导出</TheButton>
          </Space>
        </Form.Item>
      </Form>
    </div>
  );
};

class List extends React.Component {
  handleRefs = React.createRef()
  constructor(props) {
    super(props)

    this.state = {
      columns: [
        {
          title: "ID",
          dataIndex: "memberId",
          key: "memberId",
        },
        {
          title: "头像",
          dataIndex: "memberAvatar",
          key: "memberAvatar",
          render: (text) => {
            if (text) {
              return <Avatar src={<Image src={text} />} />
            } else {
              return <Avatar icon={<UserOutlined />} />
            }
          }
        },
        {
          title: "昵称",
          dataIndex: "nickName",
          key: "nickName",
        },
        {
          title: "手机号",
          dataIndex: "memberMobile",
          key: "memberMobile",
          render: (text) => {
            var reg = /^(\d{3})\d{4}(\d{4})$/;
            if (text) {
              // var memberMobile = text.toString().replace(reg, '$1****$2');
              return maskNumber(text.toString(),3,4) ;
            }
          }
        },
        {
          title: "身份",
          dataIndex: "memberType",
          key: "memberType",
          render: (text, render) => {
            let label = ''
            switch (text) {
              case 'R':
                label = '注册会员'
                break;
              case "P":
                label = '正式会员'
                break;
              case "S":
                label = "商户会员"
                break;
              default:
                label = "返回值错误"
            }
            return label;
          }
        },
        {
          title: "冻结状态",
          dataIndex: "memberStatus",
          key: "memberStatus",
          render: text => {
            let label = ''
            switch (text) {
              case 'Y':
                label = '正常'
                break
              case 'N':
                label = '冻结'
                break
              default:
                label = '返回值错误'
            }
            return label;
          }
        },
        {
          title: "注销状态",
          dataIndex: "deleted",
          key: "deleted",
          render: text => {
            let label = ''
            switch (text) {
              case 0:
                label = '正常'
                break
              case 1:
                label = '已注销'
                break
              default:
                label = '返回值错误'
            }
            return label;
          }
        },
        {
          title: "推荐人Id",
          dataIndex: "parentMemberId",
          key: "parentMemberId",
          render: (text, record) => {
            return (
              record.parentMemberId !== null ? record.parentMemberId : '-'
            )
          }
        },
        {
          title: "推荐人昵称",
          dataIndex: "parentNickName",
          key: "parentNickName",
          render: (text, record) => {
            return (
              record.parentNickName !== null ? record.parentNickName : '-'
            )
          }
        },
        {
          title: "注册时间",
          dataIndex: "memberCreatedTime",
          key: "memberCreatedTime",
        },
        {
          title: "操作",
          fixed: "right",
          render: (text, render) => {
            return (
              <div>
                <TheButton haspermi={['user:details']} onClick={() => this.props.history.push(`/users/details/${render.memberId}`)}>用户详情</TheButton>
                {/* <TheButton haspermi={['user:freeze']} onClick={() => this.openDialog("account", render.memberId)}>
                  冻结账号
                </TheButton> */}
                <TheButton haspermi={['user:function']} onClick={() => this.handleRefs.open({ id: render.memberId, mode: 'CF', type: 'user', from: "person", nickName: render.nickName })}>
                  功能封禁
                </TheButton>
                {render.whetherBannedFunction == 'Y' &&
                  <TheButton haspermi={['user:function']} onClick={() => this.handleRefs.open({ id: render.memberId, mode: 'CJ', type: 'user', from: "person", nickName: render.nickName })}>
                    功能解禁
                  </TheButton>}
                {
                  render.memberStatus == 'Y' &&
                  <TheButton haspermi={['user:account']} onClick={() => this.handleRefs.open({ id: render.memberId, mode: 'UF', type: 'user', from: "person", nickName: render.nickName })}>
                    账号封禁
                  </TheButton>
                }

                {
                  render.memberStatus == 'N' && <TheButton haspermi={['user:account']} onClick={() => this.handleRefs.open({ id: render.memberId, mode: 'UJ', type: 'user', from: "person", nickName: render.nickName })}>
                    账号解禁
                  </TheButton>
                }
                {/* <TheButton haspermi={['user:banned']} onClick={() => this.openDialog("release", render.memberId)}>
                  封禁发布
                </TheButton> */}
                <TheButton haspermi={['user:viewPetDetail']} onClick={() => this.openPetDialog(render)}>
                  查看宠物信息
                </TheButton>
                <TheButton haspermi={['user:createQRCode']} onClick={() => this.openQRCodeDialog(render)}>
                  生成二维码
                </TheButton>
              </div>
            );
          },
        },
      ],
      data: [],
      pageData: {
        pageNo: 1,
        pageSize: 10,
      },
      total: 0,
      accountVisible: false,
      releaseVisible: false,
      searchValue: {},
      type: '',
      memberId: '',
      petVisible: false,
      petColumns: [
        {
          title: '宠物种类',
          dataIndex: 'petSpecies',
          key: 'petSpecies',
          render: (text, record) => {
            let label = ''
            switch (parseInt(text)) {
              case 1:
                label = '猫猫';
                break;
              case 0:
                label = '狗狗';
                break;
            }
            return label;
          }
        },
        {
          title: '品种',
          dataIndex: 'petVarieties',
          key: 'petVarieties'
        },
        {
          title: '宠物昵称',
          dataIndex: 'petName',
          key: 'petName'
        },
        {
          title: '生日',
          dataIndex: 'birthday',
          key: 'birthday'
        },
        {
          title: '性别',
          dataIndex: 'petSex',
          key: 'petSex',
          render: (text, record) => {
            let label = ''
            switch (text) {
              case 1:
                label = '公';
                break;
              case 2:
                label = '母';
                break;
            }
            return label;
          }
        },
        {
          title: '绝育情况',
          dataIndex: 'sterilizationStatus',
          key: 'sterilizationStatus',
          render: (text, record) => {
            let label = ''
            switch (text) {
              case 'Y':
                label = '已绝育';
                break;
              case 'N':
                label = '未绝育';
                break;
            }
            return label;
          }
        },
        {
          title: '是否已打疫苗',
          dataIndex: 'vaccineStatus',
          key: 'vaccineStatus',
          render: (text, record) => {
            let label = ''
            switch (text) {
              case 'Y':
                label = '已接种';
                break;
              case 'N':
                label = '未接种';
                break;
            }
            return label;
          }
        },
        {
          title: '鼻纹',
          dataIndex: 'noseprintStatus',
          key: 'noseprintStatus',
          render: (text, record) => {
            let label = ''
            switch (text) {
              case 'Y':
                label = '已录入';
                break;
              case 'N':
                label = '未录入';
                break;
            }
            return label;
          }
        },
        {
          title: '鼻纹录入时间',
          dataIndex: 'nosePrintEntryTime',
          key: 'nosePrintEntryTime'
        },
        {
          title: '档案创建时间',
          dataIndex: 'createTime',
          key: 'createTime'
        },
        {
          title: '证件照',
          dataIndex: 'petCardShowImages',
          key: 'petCardShowImages',
          render: (text, record) => {
            return <TheImage width={80} height={80} src={text} />
          }
        },
        {
          title: '照片',
          render: (text, record) => {
            return <Space>
              <TheImage width={80} height={80} src={record.petIsImages} />
              {record.petWholeBodyImages && <TheImage width={80} height={80} src={record.petWholeBodyImages} />}
            </Space>
          }
        },
      ],
      petData: [1],
      petLoading: false,
      exportLoading: false
    };
  }

  async componentDidMount() {
    let searchParams = store.getState().searchValue
    let { pageNo, pageSize, searchValue, pathName } = searchParams

    if (searchParams && pageNo && pathName == 'user') {
      this.setState({
        searchValue: {
          ...searchParams
        },
        pageData: {
          pageNo: pageNo, pageSize: pageSize
        }
      }, () => {
        this.getData()
      })
    } else {
      this.getData()
    }

  }
  getData = async () => {
    this.setState({ loading: true })
    const { searchValue, pageData } = this.state;
    let params = {
      ...searchValue, ...pageData,
    }
    store.dispatch({
      type: 'SaveSearchValues',
      data: {
        pathName: 'user',
        ...params
      }
    })
    let data = await apiGetUserList({ ...params })
    if (data.code === 0 && data) {
      this.setState({
        data: data.data,
        pageData: {
          pageNo: data.pageNo,
          pageSize: data.pageSize
        },
        total: data.totalCount,
        loading: false
      })
    } else {
      this.setState({ loading: false })
    }
  }
  pageChange = (pageNo, pageSize) => {
    this.setState({ pageData: { pageNo, pageSize } }, () => {
      this.getData()
    })
  };
  openAdd = () => {
    this.setState({ visible: true });
  };
  dialogCancel = () => {
    this.setState({ visible: false });
  };
  openDialog = (value, memberId) => {
    this.setState({ [`${value}Visible`]: true, type: value, memberId });
  };
  dialogClose = () => {
    this.setState({ accountVisible: false, releaseVisible: false });
  };
  getSearchValue = value => {
    this.setState({ searchValue: value, pageData: { pageNo: 1, pageSize: 10 } }, () => {
      this.getData()
    })
  }
  resetValue = () => {
    this.getData()
    this.setState({ searchValue: {} }, () => {
      this.getData()
    })
  }
  openPetDialog = async (value) => {
    this.setState({ petLoading: true })
    const { memberId } = value
    let res = await apiPetArchivesPage({ memberId, pageNo: 1, pageSize: 10000 })
    if (res.data && res.code === 0) {
      this.setState({
        petData: res.data,
        petVisible: true
      })
    }
    this.setState({ petLoading: false })
  }
  openQRCodeDialog = async (value) => {
    let _that = this;
    Modal.info({
      title: '',
      centered: true,
      icon: '',
      width: 600,
      content: (
        <>
          <div id={'qrid' + value.memberId} style={{ textAlign: 'center', padding: "35px", backgroundColor: "#ffda44" }}>
            <QRCode
              value={'https://app.hqmpet.com/share/#/?memberId=' + value.memberId}
              size={450} // 二维码的大小
              fgColor="#000000" // 二维码的颜色
              includeMargin={true}
              marginSize={10}
              imageSettings={{ // 二维码中间的logo图片
                src: logoUrl,
                height: 80,
                width: 80,
                excavate: true, // 中间图片所在的位置是否镂空
              }}
              level="H"
            />
            <p style={{ fontSize: "44px", fontWeight: 400, margin: 0 }}>哈奇马生活体验馆</p>
            <p style={{ fontSize: "35px", margin: 0 }}>{value.memberId}</p>
          </div>
        </>
      ),
      okText: '关闭',
      onOk() {

      },
      afterClose() {
        console.log('asdsa')
      }
    });
    setTimeout(function () {
      // 将dom转换成png图片url
      let node = document.getElementById('qrid' + value.memberId);
      domtoimage.toPng(node)
        .then(function (dataUrl) {
          // console.log(dataUrl)
          const image = document.createElement('img')
          image.src = dataUrl
          image.style.position = "absolute"
          image.style.top = "40px"
          node.after(image)
          // node.innerHTML = `<img width=${230} height=${250} src=${dataUrl}/>`
        })
        .catch(function (error) {
          console.error('oops, something went wrong!', error);
        });
    }, 100);
  }

  petHandleCancel = () => {
    this.setState({ petVisible: false })
  }
  render() {
    const { exportLoading, columns, data, pageData, total, accountVisible, releaseVisible, type, memberId, loading, petVisible, petColumns, petData, petLoading } =
      this.state;
    return (
      <div className="p-layout-box commodity-examine">
        <SearchHeader totalCount={total} openAdd={this.openAdd} getSearchValue={this.getSearchValue} resetValue={this.resetValue} />
        <div className="p-layout-content-pagination">
          <TheTable
            scroll={{ x: "max-content", y: '63vh' }}
            columns={columns}
            dataSource={data}
            loading={loading}
          />
          <ThePagination
            pageNo={pageData.pageNo}
            pageSize={pageData.pageSize}
            total={total}
            pageChange={this.pageChange}
          />
          <TheDialog
            title={
              <div>
                <ExclamationCircleFilled
                  style={{ color: "#FAAD14", marginRight: 10 }}
                />
                冻结账号
              </div>
            }
            visible={accountVisible}
            handleCancel={this.dialogClose}
            footer={null}
            width={400}
          >
            <Banned dialogClose={this.dialogClose} type={type} reload={this.getData} memberId={memberId} />
          </TheDialog>
          {/* <TheDialog
            title={
              <div>
                <ExclamationCircleFilled
                  style={{ color: "#FAAD14", marginRight: 10 }}
                />
                封禁发布
              </div>
            }
            visible={releaseVisible}
            handleCancel={this.dialogClose}
            footer={null}
            width={400}
          >
            <Banned dialogClose={this.dialogClose} type={type} reload={this.getData} memberId={memberId} />
          </TheDialog> */}
          <TheDialog
            title={'宠物信息'}
            width={1200}
            visible={petVisible}
            handleCancel={this.petHandleCancel}
            handleOk={this.petHandleCancel}
          >
            <TheTable scroll={{ x: 'max-content', y: '30vh' }} columns={petColumns} dataSource={petData} loading={petLoading} />
          </TheDialog>
          <HandleDialog ref={ref => this.handleRefs = ref} getData={this.getData}></HandleDialog>
        </div>
      </div>
    );
  }
}

export default _connect(List);
